package com.scalar.chiptrack.tags;
//
import org.apache.struts.util.RequestUtils;
import javax.servlet.jsp.tagext.TagSupport;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Iterator;
import com.scalar.chiptrack.commons.forms.BaseResultActionForm;
import com.scalar.chiptrack.commons.bean.TableMetaDataBean;
import com.scalar.chiptrack.commons.bean.ColumnBean;
import com.scalar.chiptrack.commons.bean.ResultMetaDataBean;
import com.scalar.chiptrack.commons.bean.IRowResultBean;
import com.scalar.chiptrack.commons.Constants;
import com.scalar.chiptrack.utils.ConfigManager;

/**
 * This class contains access methods for
 */
public class SearchResultsTag extends TagSupport
{
    private String chiptracContext = null;
    private String formName = "";

    public String getFormName()
    {
        return formName;
    }

    public void setFormName( String formName )
    {
        this.formName = formName;
    }

    //this method displays the content
    public int doEndTag() throws JspException
    {
        ArrayList searchRowBeanList = null;
        JspWriter out = null;
        chiptracContext = (( HttpServletRequest )pageContext.getRequest()).getContextPath();
        Object formbean = RequestUtils.lookup(pageContext, formName, null);
        BaseResultActionForm form = null;
        if (formbean != null && formbean instanceof BaseResultActionForm)
        {
            form = (BaseResultActionForm)formbean;
        }
        else
        {
            throw new JspException("Bean not found");
        }

        try
        {
            searchRowBeanList = form.getPaginator().getPage( Integer.parseInt( form.getCurrentPageNo() ) ).getRows();
            if( (  searchRowBeanList.size() == 0 ) )
            {
                return SKIP_BODY;
            }

            out = pageContext.getOut();
            out.println( "<TABLE WIDTH='100%' border='0' cellspacing = 0 cellpadding = 0>" );
            out.println( "<TR>" );
            out.println( "<TD colspan='9'>" );

            printSearchResults( out , searchRowBeanList , form );
            out.println( "</TD>" );
            out.println( "</TR>" );
            out.println( "</TABLE>" ); //end of the table for showing the search results

        }
        catch( Exception e )
        {
            throw new JspException( e );
        }
        return EVAL_BODY_INCLUDE;
    }

    /**
     * This methods prints the search results to the JspWriter object passed as the argument
     *
     * @param out
     * @param searchRowBeanList
     * @param form
     */
    private void printSearchResults( JspWriter out, ArrayList searchRowBeanList, BaseResultActionForm form  ) throws Exception
    {
        TableMetaDataBean tableMetaDataBean = form.getTableMetaDataBean();
        ArrayList searchMetaDataBeanList = tableMetaDataBean.getColumnDetailsList( true );
        ArrayList columnBeanList = form.getColumnBeanList();
        ResultMetaDataBean searchMetaDataBean = null;

        //printing column headers
        out.println( "<TABLE WIDTH='100%' border='0' cellspacing='1' cellpadding='0'>" );
        out.println( "<TR align='center' bgcolor='#DEE1E2' class='NArialL' height='20'><font color='#FFFFFF'>" );

        Iterator iterator = searchMetaDataBeanList.iterator();
        while( iterator.hasNext() )
        {
            searchMetaDataBean = ( ResultMetaDataBean ) iterator.next();
            out.println( "<TD WIDTH='" + searchMetaDataBean.getColWidth() + "%' nowrap>" );
            Iterator columnBeanIterator = columnBeanList.iterator();
            while( columnBeanIterator.hasNext() )
            {

                ColumnBean columnBean = ( ColumnBean )columnBeanIterator.next();
                if( columnBean.getColumnName().equalsIgnoreCase( searchMetaDataBean.getColumnName() ))
                {
                    sortOrder( form, columnBean.getDbColumnName(), out, searchMetaDataBean );
                }
            }
            out.println( "</TD>" );
        }
        out.println( "</font></TR>" );

        IRowResultBean searchRowBean = null;
        int rowCount = 0;

        //printing the column data
        for( int j = 0; j < searchRowBeanList.size(); j++  )
        {
            searchRowBean = ( IRowResultBean )searchRowBeanList.get( j );

            if( rowCount % 2 == 0 )
            {
                out.println( "<TR class='NArialL' bgcolor='#DEE1E2' height='18'>" );
            }
            else
            {
                out.println( "<TR class='NArialL' bgcolor='#FFFFEE' height='18'>" );
            }
            Iterator columnBeanIterator = columnBeanList.iterator();
            while( columnBeanIterator.hasNext() )
            {
                ColumnBean columnBean = ( ColumnBean )columnBeanIterator.next();
                if( columnBean.isPrimaryColumn() )
                {
                   // out.println( "<TD width='5%' align='center'>" );
                    out.println( "<input type = 'hidden' name='list["+ j +"].id' value='" + searchRowBean.getValue( columnBean.getDbColumnName() ) + "' > ");
                    out.println( "<input type = 'hidden' name='list[" + j  + "].selected' value='false' > ");
                    /*out.println( "<input type='checkbox' align='center' name='selected' class='NArialL' onclick=\"onClickCheckBox('" +_formName +"',this,'"+ j +"')\" >");*/
                    //out.println( "</TD>");
                }
            }
            iterator = searchMetaDataBeanList.iterator();
            while( iterator.hasNext() )
            {
                searchMetaDataBean = ( ResultMetaDataBean ) iterator.next();
                if( addNoWrap( searchMetaDataBean.getColumnName() ) )
                {
                    out.println( "<TD WIDTH='" + searchMetaDataBean.getColWidth() + "%' class='NArialL' nowrap>&nbsp;&nbsp;" + getColumnData( searchRowBean, searchMetaDataBean.getColumnName(), columnBeanList ) + "</TD>" );
                }
                else
                {
                    out.println( "<TD WIDTH='" + searchMetaDataBean.getColWidth() + "%' class='NArialL'>&nbsp;&nbsp;" + getColumnData( searchRowBean, searchMetaDataBean.getColumnName(), columnBeanList ) + "</TD>" );
                }
                out.println( "</TD>" );
            }
            out.println( "</TR>" );
            rowCount++;
        }
        

        out.println( "</TABLE>" );
    }

    private void sortOrder( BaseResultActionForm form, String sortColumn, JspWriter out, ResultMetaDataBean searchMetaDataBean ) throws Exception
    {
        //System.out.println("form.getResultBean().getSortColumn() = " + form.getResultBean().getSortColumn());
        //System.out.println("form = " + form);
        //System.out.println("form.getResultBean() = " + form.getResultBean());
        //System.out.println("form.getResultBean().getSortColumn() = " + form.getResultBean().getSortColumn());
        if( form.getResultBean().getSortColumn()!=null&&form.getResultBean().getSortColumn().equalsIgnoreCase( sortColumn ) )
        {
            String sortOrder = ( Constants.SORT_ORDER_ASCE.equals( form.getResultBean().getSortOrder() ) )? Constants.SORT_ORDER_DESC : Constants.SORT_ORDER_ASCE;
            out.println( "<A href = \"javascript:sortResults('"+ sortColumn +"','"+ sortOrder + "' )\" class='NArialL' onmouseover=\"window.status='Click here to Sort by " + searchMetaDataBean.getColumnName() + "';return true\" onmouseout=\"window.status='';return true\" >" + searchMetaDataBean.getDisplayName() + "</A>&nbsp;&nbsp;&nbsp;" );
            if( Constants.SORT_ORDER_ASCE.equalsIgnoreCase( form.getResultBean().getSortOrder() ) )
            {
                out.println( "<img src='" + chiptracContext + "/jsp/includes/images/ascending.jpg' height='15' width='15'>" );
            }
            else if( Constants.SORT_ORDER_DESC.equalsIgnoreCase( form.getResultBean().getSortOrder() ) )
            {
                out.println( "<img src='" + chiptracContext + "/jsp/includes/images/descending.jpg' height='15' width='15'>" );
            }
        }
        else
        {
            out.println( "<A href = \"javascript:sortResults('"+ sortColumn +"','ASC' )\" class='NArialL' onmouseover=\"window.status='Click here to Sort by " + searchMetaDataBean.getColumnName() + "';return true\" onmouseout=\"window.status='';return true\" >" + searchMetaDataBean.getDisplayName() + "</A>&nbsp;&nbsp;&nbsp;" );
        }
    }

    /**
     * This method returns the value to be displayed under the given column from the searchRowBean object
     *
     * @param searchRowBean
     * @param columnName
     *
     * @return columnData
     */
    private String getColumnData( IRowResultBean searchRowBean, String columnName, ArrayList columnBeanList ) throws Exception
    {
        String columnData = "";
        if( !( ( columnName == null ) || ( "".equals( columnName ) ) ) )
        {
            Iterator columnBeanListIterator = columnBeanList.iterator();
            while( columnBeanListIterator.hasNext() )
            {
                ColumnBean columnBean = ( ColumnBean )columnBeanListIterator.next();
                if( columnBean.getColumnName().equalsIgnoreCase( columnName ) )
                {
                    if( columnBean.isLinkRequired() )
                    {
                         columnData = "<a href ='" + chiptracContext + columnBean.getColumnUrlBean().getBaseUrl() + searchRowBean.getValue( columnBean.getColumnUrlBean().getId() ) +"' target='"+ columnBean.getColumnUrlBean().getTarget() +"' class='NArialL' onmouseover=\"window.status='Click here to view "+ searchRowBean.getValue(columnBean.getColumnUrlBean().getName()) +" details';return true\" onmouseout=\"window.status='';return true\" >"+ searchRowBean.getValue(columnBean.getColumnUrlBean().getName()) +"</a>";
                    }
                    else if( columnBean.isColumnTypeBoolean() )
                    {
                        String isYes = ( searchRowBean.getValue( columnBean.getDbColumnName() ).equals("0"))? "Yes" : "No";
                        columnData = isYes;
                    }
                    else
                    {
                        columnData = searchRowBean.getValue( columnBean.getDbColumnName() );
                    }
                }

            }
        }
        return columnData;
    }

    /**
     * Returns if the NOWRAP attribute has to be added to this column data
     *
     * @param columnName
     * @return
     */
    private boolean addNoWrap( String columnName )
    {
        boolean noWrap = true;

        if( "DESCRIPTION".equalsIgnoreCase( columnName ) )
        {
            noWrap = false;
        }
        return noWrap;
    }

}
